<?php

namespace app\store\model\lottery;

use app\common\model\lottery\Active as ActiveModel;
use app\store\model\lottery\ActiveGoods as ActiveGoodsModel;
use app\store\model\lottery\ActivePrize as ActivePrizeModel;

/**
 * 抽奖-活动会场模型
 * Class Active
 * @package app\store\model\lottery
 */
class Active extends ActiveModel
{
    /**
     * 
     */
    public function getList($active_id = null)
    {
    	return $this->with(['goods'])
            ->where('is_delete', '=', 0)
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }

     /**
     * 新增
     */
    public function add($data)
    {
        if (!$this->onValidate($data)){
        	return false;
        }
        $data['wxapp_id'] = static::$wxapp_id;
        $data['province_id'] = static::$region['province'];
        $data['city_id'] = self::$region['city'];
        $data['active_date'] = strtotime($data['active_date']);
        $data['end_date'] = strtotime($data['end_date']);
        !isset($data['lottery_goods']) && $data['lottery_goods'] = [];
        !isset($data['lottery_prize']) && $data['lottery_prize'] = [];
        return $this->transaction(function () use ($data) {
            // 活动
            $this->allowField(true)->save($data);
            // 产品
            $this->onActiveGoodsRec($data['lottery_goods']);
            // 奖品
            $this->onActivePrize($data['lottery_prize']);
            return true;
        });
    }

    /**
     *更新 
     */
    public function edit($data)
    {
        if (!$this->onValidate($data)){
            return false;
        }
        $data['wxapp_id'] = static::$wxapp_id;
        $data['province_id'] = static::$region['province'];
        $data['city_id'] = self::$region['city'];
        $data['active_date'] = strtotime($data['active_date']);
        $data['end_date'] = strtotime($data['end_date']);
        !isset($data['lottery_goods']) && $data['lottery_goods'] = [];
        !isset($data['lottery_prize']) && $data['lottery_prize'] = [];
        return $this->transaction(function () use ($data) {
            // 活动
            $this->allowField(true)->save($data);
            // 产品
            $this->onActiveGoodsRec($data['lottery_goods']);
            // 奖品
            $this->onActivePrize($data['lottery_prize']);
            return true;
        });
    }


     /**
     * 商品关联记录
     */
    private function onActiveGoodsRec($lotteryGoodsIds)
    {
        $saveData = [];
        foreach ($lotteryGoodsIds as $goodsId) {
            $saveData[] = [
                'active_id' => $this['active_id'],
                'lottery_goods_id' => $goodsId,
                'wxapp_id' => static::$wxapp_id,
            ];
        }
        // 是否为更新
        if ($this->isUpdate) {
            $this->goods()->delete();
        }
        if ($this->is_buy == '20') {
            $this->goods()->delete();
            return true;
        }
        return (new ActiveGoodsModel)->isUpdate(false)->saveAll($saveData);
    }


    /**
     * 添加活动奖品
     */
    private function onActivePrize($lotteryPrizeIds)
    {
        $saveData = [];
        foreach ($lotteryPrizeIds as $prizeId) {
            $saveData[] = [
                'active_id' => $this['active_id'],
                'prize_id' => $prizeId,
                'wxapp_id' => static::$wxapp_id,
            ];
        }
        // 是否为更新
        if ($this->isUpdate) {
            $this->prize()->delete();
        }
        return (new ActivePrizeModel)->isUpdate(false)->saveAll($saveData);
    }

    /**
     * 表单验证
     * @param $data
     * @return bool
     */
    private function onValidate($data)
    {
        // 新建验证 活动日期是否已存在
        if (!$this->isUpdate && $this->isExistActiveDate($data)) {
            $this->error = '该活动日期已存在';
            return false;
        }
        if (!$this->isExistActivePrize($data)) {
            $this->error = '没有设置奖品';
            return false;
        }
        if (!$this->onValidateLotteryGoods($data)) {
            $this->error = '您还没有选择商品';
            return false;
        }
        if (!$this->onValidateTime($data)) {
            $this->error = '截至时间不能小于活动开始时间';
            return false;
        }
        if (!$this->isUpdate && $this->isExistActiveQi($data)) {
            $this->error = '该活动期数已存在';
            return false;
        }
        return true;
    }


    /**
     * 活动日期是否已存在
     * @param $date
     * @return bool
     */
    private function isExistActiveDate($data)
    {
        return !!(new static)
        	->where('active_date', '=', strtotime($data['active_date']))
            ->where('is_delete', '=', 0)
            ->value('active_id');
    }

    /**
     * 
     */
    private function isExistActiveQi($data)
    {
        return !!(new static)
            ->where('active_qi', '=', $data['active_qi'])
            ->where('is_delete', '=', 0)
            ->value('active_id');
    }

    /**
     * 设置奖品
     */
    private function isExistActivePrize($data)
    {
        if (!isset($data['lottery_prize']) || empty($data['lottery_prize'])) {
            return false;
        }
        return true;
    }

    /**
     * 验证截至时间
     */
    private function onValidateTime($data)
    {
        if (strtotime($data['end_date']) <= strtotime($data['active_date']) ) {
            return false;
        }
        return true;
    }


    /**
     * 验证是否选择商品
     */
    private function onValidateLotteryGoods($data)
    {
        // 是否必须购买指定产品
        if ($data['is_buy'] == '20') {
            return true;
        }
        if (!isset($data['lottery_goods']) || empty($data['lottery_goods'])) {
            return false;
        }
        return true;
    }

    //
    public function getGoodsListByActiveId($active_id)
    {
        $data = [];
        foreach (ActiveGoodsModel::getGoodsListByActiveId($active_id) as $item) {
            $data[] = [
                'goods_id' => $item['lottery_goods_id'],
                'goods_name' => $item['goods']['goods_name'],
                'goods_image' => $item['goods']['goods_image'],
            ];
        }
        return $data;
    }


    public function getPrizeListByActiveId($active_id)
    {
        $data = [];
        foreach (ActivePrizeModel::getPrizeListByActiveId($active_id) as $item) {
            $data[] = [
                'prize_id' => $item['prize_id'],
                'prize_name' => $item['name'],
                'prize_image' => $item['image']['file_path'],
            ];
        }
        return $data;
    }


    /**
     * 修改状态
     */
    public function setStatus($state)
    {
        return $this->allowField(true)->save(['status' => $state ? 1 : 0 ]) !== false;
    }


    /**
     * 软删除
     */
    public function setDelete()
    {
        // 将该活动设置为已删除
        return $this->allowField(true)->save(['is_delete' => 1]);
    }


    /**
     *活动期数
     */
    public static function lotteryActiveQi()
    {
        return date('Ymd');
    }


}